import React from 'react';
import { WeaRichText, WeaLocaleProvider ,WeaTools} from 'ecCom';
import { ReplyAddStore } from '../../stores/reply/add';
import { observer } from 'mobx-react';
import { Icon,Button } from 'antd';
import CubeAt from "../cube-at";
import * as Utils from "../../util";
import { writeLog } from "../../util/modeUtil";
const getLabel = WeaLocaleProvider.getLabel;
import jQuery from "jquery";
import $ from "jquery";
import loadjs from "loadjs";

export interface ReplyAddProps {
    replyAdd: ReplyAddStore;
    isShowSignInput?: boolean;
    editorId?: string;
    visible?: boolean;
    params: any;
}
const window = WeaTools.WindowFunc.getTop();
let allNames: any[] = [];


@observer
export default class RightReplyAdd extends React.Component<ReplyAddProps, any> {
    rtInstance:any;

    constructor(props) {
        super(props);
        const { remark, visible } = props;
        this.state = {
            remark: remark,
            visibleComponent: '',
            visible: visible
        }

        if (!window.CK_REF) {
            window.CK_REF = {};
        }
    }
    /**
     *  回复评富文本框底部按钮
     */
    getbottomBar = () => {
        const { replyAdd,params } = this.props;
        const{billid,formId,modeId}=params;
        const{showbuttons}=replyAdd;
        let bottomBarConfig: any[] = [];
            showbuttons.forEach(buttoninfo => {
                if(buttoninfo.isdefault && buttoninfo.fieldhtmltype == "3"){
                    if(buttoninfo.type == "37"){
                        bottomBarConfig.push({
                            isBlog: true,
                            name: "Browser",
                            show: (
                                <div className="wea-cb-item">
                                    <span className={"wea-cbi-icon-Document"} />
                                    <span className="wea-cbi-text"> <i className='icon-coms-Journal'/> {getLabel(58, "文档")}</span>
                                </div>
                            ),
                            type: "37",
                            isSingle: false,
                            customParams:{linkUrl:buttoninfo.buttonProps.linkUrl,isdefault:buttoninfo.isdefault,fieldid:buttoninfo.fieldid},
                            title: getLabel(58, "文档")
                        });
                    }else if(buttoninfo.type == "152"){
                        bottomBarConfig.push({
                            isBlog: true,
                            name: "Browser",
                            show: <div className="wea-cb-item">
                                <span className={"wea-cbi-icon-Process"} />
                                <span className="wea-cbi-text"><i className='icon-coms-Workflow-o'  /> {getLabel(18015, "流程")}</span>
                            </div>,
                            type: "152",
                            isSingle: false,
                            customParams:{linkUrl:buttoninfo.buttonProps.linkUrl,isdefault:buttoninfo.isdefault,fieldid:buttoninfo.fieldid},
                            title: getLabel(18015, "流程")
                        })
                    }else if(buttoninfo.type == "18"){
                        bottomBarConfig.push({
                            isBlog: true,
                            name: "Browser",
                            show: <div className="wea-cb-item">
                                <span className={"wea-cbi-icon-Personnel"} />
                                <span className="wea-cbi-text"><i className='icon-coms-currency-Customer'/> {getLabel(136, "客户")}</span>
                            </div>,
                            type: "18",
                            isSingle: false,
                            customParams:{linkUrl:buttoninfo.buttonProps.linkUrl,isdefault:buttoninfo.isdefault,fieldid:buttoninfo.fieldid},
                            title: getLabel(136, "客户")
                        })
                    }else if(buttoninfo.type == "135"){
                        bottomBarConfig.push({
                            isBlog: true,
                            name: "Browser",
                            show: <div className="wea-cb-item">
                                <span className={"wea-cbi-icon-Project"} />
                                <span className="wea-cbi-text"><i className='icon-coms-task-list'/> {getLabel(101, "项目")}</span>
                            </div>,
                            type: "135",
                            isSingle: false,
                            customParams:{linkUrl:buttoninfo.buttonProps.linkUrl,isdefault:buttoninfo.isdefault,fieldid:buttoninfo.fieldid},
                            title: getLabel(101, "项目")
                        })
                    }
                }else if(buttoninfo.isdefault && buttoninfo.fieldhtmltype == "6"){
                    let secId =replyAdd.seccategory
                    if(buttoninfo.seccategory){
                        secId = buttoninfo.seccategory;
                    }
                    bottomBarConfig.push({
                        isBlog: true,
                        name: "Upload",
                        show: <div className="wea-cb-item">
                            <span className={"wea-cbi-icon-File"} />
                            <span className="wea-cbi-text"><Icon type='paper-clip' /> {getLabel(156, '附件')}</span>
                        </div>,
                        uploadId: "replyUpload",
                        uploadUrl: "/api/formmode/card/replyUpload?category=1&from=reply&mainId=" + replyAdd.maincategory + "&subId=" + replyAdd.subcategory + "&secId=" +secId 
                        + "&modeid=" + modeId+ "&formid=" + formId+ "&billid=" + billid,
                        autoUpload: true,
                        multiSelection: false,
                        customParams:{isdefault:buttoninfo.isdefault,fieldid:buttoninfo.fieldid},
                        category: replyAdd.maincategory + "," + replyAdd.subcategory + "," + replyAdd.seccategory,
                        btnSize: "small"
                    })  
                }
                if(!buttoninfo.isdefault){
                    if(buttoninfo.fieldhtmltype == "3"){
                        bottomBarConfig.push({
                            isBlog: true,
                            name: "Browser",
                            show: <div className="wea-cb-item">
                                <span className="wea-cbi-text"><i className='icon-coms-task-list'/> {buttoninfo.fieldlabelname}</span>
                            </div>,
                            customParams:{linkUrl:buttoninfo.buttonProps.linkUrl,isdefault:buttoninfo.isdefault,fieldid:buttoninfo.fieldid},
                           ...buttoninfo.buttonProps
                        })
                    }else if(buttoninfo.fieldhtmltype == "6"){
                        let secId =replyAdd.seccategory
                        if(buttoninfo.seccategory){
                            secId = buttoninfo.seccategory;
                        }
                        bottomBarConfig.push({
                            isBlog: true,
                            name: "Upload",
                            show: <div className="wea-cb-item">
                                <span className={"wea-cbi-icon-File"} />
                                <span className="wea-cbi-text"><Icon type='paper-clip' /> {buttoninfo.fieldlabelname}</span>
                            </div>,
                            uploadId: "replyUpload",
                            uploadUrl: "/api/formmode/card/replyUpload?category=1&from=reply&mainId=" + replyAdd.maincategory + "&subId=" + replyAdd.subcategory + "&secId=" + secId
                            + "&modeid=" + modeId+ "&formid=" + formId+ "&billid=" + billid,
                            autoUpload: true,
                            multiSelection: false,
                            customParams:{isdefault:buttoninfo.isdefault,fieldid:buttoninfo.fieldid},
                            category: replyAdd.maincategory + "," + replyAdd.subcategory + "," + buttoninfo.seccategory,
                            btnSize: "small"
                        })
                    }
                }
                
            });
        
        return bottomBarConfig;
    }
    toolsChange = (name, _, list, type,customParams) => {
        (this.rtInstance as any).focus('last');
        let str = '';
        let linkUrl = customParams?customParams.linkUrl:'';
        let isdefault = customParams?customParams.isdefault:false;
        let fieldid = customParams?customParams.fieldid:'0';
        const mirror = {
             37: "doc",
             task: "task",
             18: "crm",
             152: "workflow",
             135: "project",
            workplan: "workplan",
            blogTemplate: "blogTemplate"
        }
        list.map(item => {
            if (name === 'Upload' && type === 'image') {
                str += '<img class="formImgPlay" src="' + item.filelink + '" data-imgsrc="' + (item.loadlink || item.filelink) + '" />'
            }
            if (name === 'Upload' && type === 'file') {
                    str += (item.filelink + '<br>')
            }
            if (name === 'Browser') {
                // if (mirror[type] == "doc") {//文档
                //     str += (type === 'blogTemplate' ? item.name : `<a href="javascript:modeopenFullWindowHaveBar('/spa/document/index.jsp?id=${item.id}')"  linkid='${item.id}' linkType='${mirror[type]}' onclick="try{return openAppLink(this,${item.id});}catch(e){}" ondblclick='return false;'  unselectable='off' contenteditable='false' style='cursor:pointer;text-decoration:underline !important;margin-right:8px'>${item.name || item.showname}</a>&nbsp;&nbsp;&nbsp;`)
                // }
                // // else if(mirror[type] == "task"){
                // //     str += (type === 'blogTemplate' ? item.name : `<a href="javascript:modeopenFullWindowHaveBar('/spa/document/index.jsp?id=${item.id}')"  linkid='${item.id}' linkType='${mirror[type]}' onclick="try{return openAppLink(this,${item.id});}catch(e){}" ondblclick='return false;'  unselectable='off' contenteditable='false' style='cursor:pointer;text-decoration:underline !important;margin-right:8px'>${item.name || item.showname}</a>&nbsp;&nbsp;&nbsp;`)
                // // }
                // else if (mirror[type] == "crm") {//客户
                //     str += (type === 'blogTemplate' ? item.name : `<a href="javascript:modeopenFullWindowHaveBar('/spa/crm/static/index.html#/main/crm/customerView?customerId=${item.id}')"  linkid='${item.id}' linkType='${mirror[type]}' onclick="try{return openAppLink(this,${item.id});}catch(e){}" ondblclick='return false;'  unselectable='off' contenteditable='false' style='cursor:pointer;text-decoration:underline !important;margin-right:8px'>${item.name || item.showname}</a>&nbsp;&nbsp;&nbsp;`)
                // } else if (mirror[type] == "workflow") {//流程
                //     str += (type === 'blogTemplate' ? item.name : `<a href="javascript:modeopenFullWindowHaveBar('/workflow/request/ViewRequestForwardSPA.jsp?isrequest=1&requestid=${item.id}')"  linkid='${item.id}' linkType='${mirror[type]}' onclick="try{return openAppLink(this,${item.id});}catch(e){}" ondblclick='return false;'  unselectable='off' contenteditable='false' style='cursor:pointer;text-decoration:underline !important;margin-right:8px'>${item.name || item.showname}</a>&nbsp;&nbsp;&nbsp;`)
                // } else if (mirror[type] == "project") {//项目
                //     str += (type === 'blogTemplate' ? item.name : `<a href="javascript:modeopenFullWindowHaveBar('/spa/prj/index.html#/main/prj/projectCard?prjid=${item.id}')"  linkid='${item.id}' linkType='${mirror[type]}' onclick="try{return openAppLink(this,${item.id});}catch(e){}" ondblclick='return false;'  unselectable='off' contenteditable='false' style='cursor:pointer;text-decoration:underline !important;margin-right:8px'>${item.name || item.showname}</a>&nbsp;&nbsp;&nbsp;`)
                // } else {
                //     str += (type === 'blogTemplate' ? item.name : `<a href='javascript:void(0)'  linkid='${item.id}' linkType='${mirror[type]}' onclick='try{return openAppLink(this,${item.id});}catch(e){}' ondblclick='return false;'  unselectable='off' contenteditable='false' style='cursor:pointer;text-decoration:underline !important;margin-right:8px'>${item.name || item.showname}</a>`)
                // }
                if(isdefault){
                    str += (type === 'blogTemplate' ? item.name : `<a href="javascript:modeopenFullWindowHaveBar('${linkUrl+item.id}')"  linkid='${item.id}' linkType='${mirror[type]}' onclick="try{return openAppLink(this,${item.id});}catch(e){}" ondblclick='return false;'  unselectable='off' contenteditable='false' style='cursor:pointer;text-decoration:underline !important;margin-right:8px'>${item.name || item.showname}</a>&nbsp;&nbsp;&nbsp;`)
                }else{
                    str += (type === 'blogTemplate' ? item.name : `<abbr class='custom' id='${fieldid+'_'+item.id}' name='${item.name}'><a href="javascript:modeopenFullWindowHaveBar('${linkUrl+item.id}')"  linkid='${item.id}' linkType='${mirror[type]}' onclick="try{return openAppLink(this,${item.id});}catch(e){}" ondblclick='return false;'  unselectable='off' contenteditable='false' style='cursor:pointer;text-decoration:underline !important;margin-right:8px'>${item.name || item.showname}</a></abbr>`)
                }
               if(mirror[type] == "task"){
                    str += (type === 'blogTemplate' ? item.name : `<a href="javascript:modeopenFullWindowHaveBar('/spa/document/index.jsp?id=${item.id}')"  linkid='${item.id}' linkType='${mirror[type]}' onclick="try{return openAppLink(this,${item.id});}catch(e){}" ondblclick='return false;'  unselectable='off' contenteditable='false' style='cursor:pointer;text-decoration:underline !important;margin-right:8px'>${item.name || item.showname}</a>&nbsp;&nbsp;&nbsp;`)
                }
            }
        })
        return str;
    }

    getAtInfo() {
        const { replyAdd, params = {} } = this.props;
        return replyAdd.getAtInfo(params);
    }

    setAtInfo = (k, v) => {
        const { replyAdd, params = {} } = this.props;
        replyAdd.setAtInfo(k, v, params);
    }

    componentWillMount() {
        const { replyAdd, params = {} } = this.props;
        const atInfo = this.getAtInfo();
        const { time = '' } = atInfo;
        let key = "cube_at_" + params.modeId + "_" + params.billid;
        let now: any = new Date().getTime();
        let isNeedLoad = true;
        if (window.__atdata && time && !isNaN(time)) {
            if (now - time < 1000 * 60 * 3) {//小于3分钟，不需要再次加载
                isNeedLoad = false;
            }
        }
        let tempatitems: any = [];
        let setAtInfo = this.setAtInfo.bind(this);
        if (isNeedLoad) {
            jQuery.ajax({
                url: '/api/cube/new/card/getAtUsers',
                type: 'GET', //GET
                data: { modeid: params.modeId, billid: params.billid },
                success: function (result) {
                    setAtInfo("time", now);
                    const response = JSON.parse(result);
                    tempatitems = [];
                    response.operators.map(o => {
                        tempatitems.push(o);
                    });
                    replyAdd.atInfo[key + "_data"] = { atitems: tempatitems, _atitems: tempatitems.slice(0, 100) };
                    window.__atdataready = true;
                    window.__atdata = tempatitems;
                }
            });
        } else {
            tempatitems = window.__atdata;
            window.__atdataready = true;
            replyAdd.atInfo[key + "_data"] = { atitems: tempatitems, _atitems: tempatitems.slice(0, 100) };
        }
    }

    getExtendsBar = () => {
        const { editorId, params, replyAdd } = this.props;
        const { visibleComponent } = this.state;
        const extentsConfig = [
            {
                name: 'Upload',
                type: 'image',
                show: <div className="wea-cb-item">
                    <span className={`wea-cbi-icon cke_button_icon cke_button__image_icon`} />
                </div>,
                uploadUrl: '/api/formmode/card/uploadimage',
                category: 'all',
                limitType: 'jpg,gif,png',
                title: '上传图片',
                needLoading: false
            },
            {
                name: 'Component',
                show: <CubeAt
                    editorId={editorId}
                    appendHtmlToCKEditor={this.addAtInfo.bind(this)}
                    visible={visibleComponent === 'CubeAt'}
                    showComponent={this.showComponent.bind(this)}
                    params={params}
                    replyAdd={replyAdd}
                />
            },
            {
                name: 'Component',
                show: <i title={getLabel('128961', "清除内容")} className="icon-mode-close" onClick={replyAdd.clearContent} />
            },
        ]
        return extentsConfig;
    }

    getRightBar = () => {
        const { replyAdd } = this.props;
        const disabled = replyAdd.content ? false:true;
        let bottomBarRight = {
            width: 85,
            Component: (
                <span className="wea-rich-text-toolbar-bottom-item" style={{ position: "relative" }}>
                    <Button disabled={disabled} className="wea-button-release" type="primary"
                    loading={replyAdd.loading} onClick={replyAdd.onOk} >
                        <span>{getLabel(615, '提交')}</span>
                    </Button>
                </span>
            )
        };
        return bottomBarRight;
    }

    componentDidMount() {
        const { editorId = "" } = this.props;
        window.CK_REF[editorId] = this.rtInstance;
    }

    showComponent(componet) {
        let extents = jQuery(".wea-rich-text-extents");
        if (extents.length > 0) {
            let left = extents[0].offsetLeft;
            if (left < 160) {
                jQuery(".wfat-content").addClass("wfat-content-right");
            } else {
                jQuery(".wfat-content").removeClass("wfat-content-right");
            }
        }
        this.setState({ visibleComponent: componet });
    }

    addAtInfo(html) {
        const { editorId = "" } = this.props;
        let _html = html;
        if(window.CK_REF[editorId]){
            const instances = window.CK_REF[editorId].getEditor().ui.instances;
            if (instances) {
                const font = instances.Font['_'].value || '微软雅黑';
                const fontsize = instances.FontSize['_'].value || '12';
                _html = `<span style="font-family:'${font}';font-size:${fontsize}px;" >${html}</span>`;
            }
        }
        this.appendHtmlToCKEditor(_html);
    }
    appendHtmlToCKEditor(html, pos?) {
        if (pos) {
            this.rtInstance['insertHTML'](Utils.convertSpecialChar(html), pos);
            const el = this.rtInstance;
            const me = this;
            $(el).off("click").on("click", function (_) {
                me.setState({ visibleComponent: '' });
            });
        } else {
            this.rtInstance['insertHTML'](Utils.convertSpecialChar(html));
        }
    }


    initAutoAt(ifr) {
        const { editorId } = this.props;
        const me = this;
        const ckeditor = this.rtInstance;
        try {
            let datas = window.__atdata;
            if (window.__atdataready != true || !!!datas) {
                setTimeout(function () {
                    me.initAutoAt(ifr);
                }, 1000);
                return;
            }

            let allatids = ",";
            if (allNames.length == 0) {
                jQuery.map(datas, function (value, _) {
                    if (allatids.indexOf("," + value.uid + ",") == -1) {
                        allatids += value.uid + ",";
                        allNames.push({ 'id': value.uid, 'name': value.data, 'py': value.datapy || "" });
                    }
                });
            }
            let names = allNames;
            let at_config = {
                at: "@",
                data: names,
                tpl: "<li data-value='@${name}'>${name}</li>",
                insert_tpl: "<a href='/spa/hrm/index_mobx.html#/main/hrm/card/cardInfo/${id}' atsome='@${id}' contenteditable='false' style='cursor:pointer;text-decoration:none !important;margin-right:8px;color:#2777c1!important;' target='_blank'>${atwho-data-value}</a>",
                limit: 100,
                show_the_at: true,
                start_with_space: false,
                with_repeat_matcher: false,
                search_key_py: 'py',
                ckeditor: ckeditor,
                editorId: editorId,
                appendHtmlToCKEditor: this.appendHtmlToCKEditor,
                pageIndex:1,
                pageSize:20,
                save:this.saveAt,
            }
            let ifrBody = ifr.contentDocument.body;
            jQuery(ifrBody)
                .atwho("setIframe", ifr)
                .atwho(at_config)
                .on("inserted.atwho", function(a,b,c) {});
                const atwhoblockobj = jQuery(".atwho-view");
                atwhoblockobj &&
                atwhoblockobj.perfectScrollbar({
                    horizrailenabled: false,
                    zindex: 11111
                });
        } catch (e) {
            writeLog("", e)
        }
    }
    saveAt = () =>{
        const ck:any = this.rtInstance;
        if(ck){
            ck.editor.undoManager.save()    
        }
    }
    loadReady =(info) =>{
        if(info == 'ready'){
            const { setEditor } = this.props.replyAdd;
            allNames = [];
            this.loadJSAndInitAt();
            setEditor(this.rtInstance.editor,this.loadJSAndInitAt)
        }
    }

    loadJSAndInitAt = () =>{
        const ckeditorid = this.rtInstance.editor.container.getId();
        const init = () => this.initAutoAt($(`#${ckeditorid}`).find('iframe')[1]);
        loadjs.isDefined("atwhoJS")
        ? loadjs.ready("atwhoJS", init)
        : loadjs(
            [
            "/cloudstore/resource/pc/atwho/jquery.atwho_wev8.js",
            "/cloudstore/resource/pc/atwho/jquery.nicescroll_wev8.js",
            "/cloudstore/resource/pc/atwho/jquery.caret_wev8.js",
            "css!/cloudstore/resource/pc/atwho/jquery.atwho_wev8.css"
            ],
            "atwhoJS",
            init
        );
        // 加载高度
        const editor = this.rtInstance.editor;
        const body = editor.document.getBody()
        if(body && body.$){
            const ht = body.getStyle('height');
            if (!ht || ht !== '100px') {
                body.setStyle("height", '100px');   
            }
        }
    }
    getInstance = ins => {
        if (!this.rtInstance) {
           this.rtInstance = ins;
        }
      }

    render() {
        const { replyAdd } = this.props;
        return (
            <div className="cube-reply-add">
                <WeaRichText
                    ref={this.getInstance}  //'WeaRichTextAdd'
                    value={replyAdd.content}
                    ckConfig={{
                        toolbar: [
                            { nane: "document", items: ["Source"] },
                            { name: "paragraph", items: ["JustifyLeft", "JustifyCenter", "JustifyRight", "-", "NumberList", "BulletedList"] },
                            { name: "styles", items: ["Format", "Font", "FontSize"] },
                            { name: "color", items: ["TextColor"] },
                            { name: "basicstyles", items: ["Bold", "Italic", "Underline", "Strike"] },
                            { name: "insert", items: ["Table", "Smiley"] },
                        ],
                        extraPlugins: 'autogrow',
                        height: 100,
                        autoGrow_minHeight: 100,
                        autoGrow_maxHeight: 100,
                        removePlugins: 'resize',
                        uploadUrl: '/api/formmode/card/uploadimage',
                    }}
                    extentsConfig={this.getExtendsBar()}
                    bottomBarConfig={this.getbottomBar()}
                    bottomBarRight={this.getRightBar()}
                    onChange={replyAdd.onChange}
                    onToolsChange={this.toolsChange}
                    onStatusChange={(info)=>{this.loadReady(info)}}
                />
            </div>
        )
    }
}

